<template>
    <div id="content">
        <!-- 地图 -->
        <div id="mapBox"/>
        <!-- 搜索框 -->
        <div id="contain-tool">
            <div id="contain-search">
                <!-- 输入框 -->
                <input id="keyword" class="input-search" placeholder="搜索站点位置..." maxlength="256"/>
                <!-- 搜索icon -->
                <img class="icon-search" src="../images/icon/search.png"/>
            </div>
        </div>

        <!-- 弹窗 -->
        <a-modal
                :title="carListModal.chargeInfo.parkName + `\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0占有率：`+  (carListModal.chargeInfo.carRate*100).toFixed(2)+`%`+  `\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0实收(`+ carListModal.chargeInfo.sumRealityMoney/100 +`元/`+carListModal.chargeInfo.countReality+`笔)` +` \u00A0\u00A0\u00A0\u00A0\u00A0应收(`+carListModal.chargeInfo.sumShouldMoney/100+`元/`
                    +carListModal.chargeInfo.countShould+`笔)`"
                :visible="carListModal.visible"
                @cancel="hideCarModal">
            
            <template slot="footer">
                <div style="display: flex; height: 36px; justify-content: flex-end;">
                    <div class="box-popup-parking">
                        <div>总车位：</div>
                        <div style="color: #3ab54a; margin-right: 20px;">{{carListModal.chargeInfo.sumTruckSpace || 30}}</div>
                        <div>空闲车位：</div>
                        <div style="color: #f36535;">{{carListModal.chargeInfo.unUseTruckSpace || 20}}</div>
                    </div>
                </div>
               
            </template>

            <div style="display: flex; flex-wrap: wrap; height: 500px; overflow: auto;">
                <template v-for="car in carListModal.dataList">
                    <div class="item-car" :key="car.id">
                        <img class="icon-car" :src="getCarIcon(car.status)">
                        <div class="text-num">
                            <div>{{car.imei}}</div>
                            <div style=" margin-left: 10px;">
                                <div v-if="car.status == 1">空闲</div>
                                <div style="color: #34ba4b;" v-else>{{getCarStatus(car.status)}}</div>
                            </div>
                        </div>
                        <div class="text-plate">
                            <template v-if="car.licencePlate">
                                车牌: {{car.licencePlate}}
                            </template>
                            <template v-else>
                            </template>
                        </div>
                    </div>
                </template>
            </div>

        </a-modal>
    </div>
</template>

<script>
    import parkingSpace from '../../src/api/ParkingSpace'

    const ImageNormal = require("../assets/car.png");
    const ImageNormal2 = require("../assets/car2.png");

    const carList = [
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
        {imgUrl: require('../assets/car.png'), site: " 1-01", state: '空闲'},
    ];

    export default {
        name: "parkingSpace",
        data() {
            return {
                //搜索框
                inputContent: "",
                poiList: [],
                //地图
                content: [],
                position: {},
                state: 0,
                condition: {},
                list: [], //停车位列表
                normal: "",
                active: "",
                parkList: [],

                locationList: undefined,

                /* 模态框 */
                carListModal: {
                    visible: false,
                    dataList: [],
                    chargeInfo: {
                        carRate: "",
                        countReality: "",
                        countShould: "",
                        countShoutButNot: "",
                        parkName: "",
                        sumRealityMoney: "",
                        sumShouldButNotMoney: "",
                        sumShouldMoney: ""
                    },
                }

            }
        },

        mounted() {
            //初始化数据
            this.$store.dispatch('showHead');
            this.initMap();
            this.init();
        },

        methods: {

            /* ------------------------ 初始化 ------------------------ */
            initMap() {
                this.map = new AMap.Map('mapBox', {
                    zoom: 12, //缩放级别
                    viewMode: '3D', //使用3D视图
                    // center:[116.205467,39.907761]
                });
                this.map.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => this.pluginCallback());

                this.map.on('zoomchange', () => {
                    let zoom = this.map.getZoom();
                    if (zoom < 15) {
                        this.drawBuild();
                    } else {
                        // this.drawLocation();
                        this.loadLocationList();
                    }
                });
            },

            init() {
                let active = this.active, normal = this.normal;
                /* ------------------ API ------------------ */
                this.loadBuildList();
            },

            /* ------------------------ API ----------------------------- */
            loadBuildList() {
                let {lng, lat} = this.map.getCenter();
                let condition = {longitude: lng, latitude: lat, radius: 10000000000000000};
                parkingSpace.getPark(condition)
                    .then((data, code) => {
                        if (data.code === 2000) {
                            this.parkList = data.data;
                            this.drawBuild()
                        }
                    })
                    .catch(error => {
                        this.$message.error("加载列表失败");
                    })
            },

            loadLocationList() {
                if (this.locationList) {
                    this.drawLocation();
                    return;
                }
                let {lng, lat} = this.map.getCenter();
                let condition = {longitude: lng, latitude: lat, radius: 10000000000000000};
                parkingSpace.getParkPoint(condition)
                    .then((data, code) => {
                        if (data.code === 2000) {
                            this.locationList = data.data;
                            this.drawLocation();
                        }
                    })
                    .catch(err => {
                        this.$message.error("加载列表失败");
                    })
            },

            changeZIndex(parkId) {
                /* 置顶 */
                let markers = this.map.getAllOverlays() || [];
                markers.forEach(item => {
                    let data = item.getExtData();
                    if(!data || !data.parkId) return ;
                    item.setzIndex(parkId == data.parkId ? 101 : 100);
                })
            },

            showCarModal(parkId) {
                let condition = {parkId, curr: 1, limit: 100}
                parkingSpace.getTruckSpaceListByParkId(condition)
                    .then((data, code) => {
                        let {list} = data.data;
                        if (list.length == 0) {
                            this.$message.info("当前没有车位");
                            return;
                        }
                        this.carListModal.visible = true;
                        this.carListModal.dataList = list;
                    })
                    .catch(error => {
                        this.$message.error(error.msg)
                    });
                let condition2 = {parkId: parkId};
                parkingSpace.getChargeInfo(condition2).then((data) => {
                    this.carListModal.chargeInfo = data.data;
                }).catch(err => {
                    this.$message.error(err.msg);
                })

            },

            hideCarModal() {
                this.carListModal.visible = false;
            },

            /* ------------------------ 地图事件 ------------------------ */
            pluginCallback() {
                let autoOptions = {
                    city: "北京", //城市，默认全国
                    input: "keyword"//使用联想输入的input的id
                };
                let autocomplete = new AMap.Autocomplete(autoOptions);
                let placeSearch = new AMap.PlaceSearch({
                    city: '北京',
                    map: this.map,
                });
                AMap.event.addListener(autocomplete, "select", (e) => {
                    placeSearch.setCity(e.poi.adcode);
                    placeSearch.search(e.poi.name, (status, result) => this.placeSearchCallBack(status, result));
                });
            },

            placeSearchCallBack(status, result) {
                if (status == 'complete') {
                    let count = result.poiList.count;
                    if (count > 0) {
                        let pois = result.poiList.pois[0];
                        let location = pois.location;
                        let lng = location.lng;
                        let lat = location.lat;
                        this.map.setCenter([lng, lat]); //设置地图中心点
                        //清除所有覆盖物！
                        // result.poiList = [];
                        this.map.clearMap();
                        this.init()
                    }
                } else if (status == 'error') {
                    console.error("搜索失败！");
                } else if (status == 'no_data') {
                    console.log("无搜索结果");
                } else {
                    console.log("未知！");
                }
            },

            /* ------------------------ 绘制事件 ------------------------ */
            drawBuild() {
                if (this.state == 1) return;
                this.state = 1;
                /* --------------------- 绘制 --------------------- */
                this.map.clearMap();
                let parkList = this.parkList;
                let {active, normal} = this;
                parkList.forEach(value => {
                    let lng = value.coordinateX;
                    let lat = value.coordinateY;
                    let sumShouldMoney = "实收:" + value.sumShouldMoney / 100 + "元";
                    let truckSpaceRate = "占有率:" + (value.truckSpaceRate * 100).toFixed(2) + "%";
                    let parkName = value.parkName.slice(0, 2);
                    this.drawSingleBuild(lng, lat, sumShouldMoney, truckSpaceRate, parkName, active, normal, value.id)
                });
            },

            //添加marker标记
            drawSingleBuild(lng, lat, parkName, truckSpaceRate, standardName, active, normal, id) {
                let marker = new AMap.Marker({
                    extData: { parkId: id },
                    map: this.map,
                    position: [lng, lat],
                    content: this.createInfoWindow(parkName, truckSpaceRate, standardName, active, normal), // 自定义点标记覆盖物内容
                    anchor: "bottom-center", // 设置锚点方位
                    offset: new AMap.Pixel(0, -122) // 相对于基点的偏移位置
                });

                let circle = new AMap.Circle({
                    extData: { parkId: id },
                    map: this.map,
                    center: [lng, lat],         // 设置线覆盖物路径
                    radius: 5,
                    strokeColor: "#f1fffd",     // 边框线颜色
                    strokeOpacity: 0.3,         // 边框线透明度
                    strokeWeight: 3,            // 边框线宽
                    fillColor: "#e7f3ff",       // 填充色
                    fillOpacity: 0.3            // 填充透明度
                });

                marker.on('click', (e) => this.changeZIndex(id))
                marker.on('dblclick', (e) => this.showCarModal(id))
                return { marker, circle }
            },

            drawLocation() {
                if (this.state == 4) return;
                this.map.clearMap();
                this.state = 4;
                this.locationList.forEach(item => {
                    this.drawItemLocation(item.longitude, item.latitude, item.licencePlate, item.status)
                })
            },

            drawItemLocation(lng, lat, title, status) {
                let marker = new AMap.Marker({
                    map: this.map,
                    position: [lng, lat],   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                    title,
                    content: this.createInfoWindow2(status),
                    anchor: "bottom-center", // 设置锚点方位
                    offset: new AMap.Pixel(0, 0) // 相对于基点的偏移位置
                });
            },

            //自定义信息窗体
            createInfoWindow2(status) {
                let info = document.createElement("div");
                let state1 = "//vdata.amap.com/icons/b18/1/2.png";
                let state2 = "https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png";
                info.className = "input-card content-window-card";
                // 定义底部内容
                let bottom = document.createElement("div");
                bottom.className = "info-bottom";
                bottom.style.position = 'relative';
                bottom.style.top = '0px';
                bottom.style.margin = '0 auto';
                let sharp = document.createElement("img");
                sharp.src = status == 2 ? state1 : state2;
                bottom.appendChild(sharp);
                info.appendChild(bottom);
                return info;
            },

            //构建自定义信息窗体
            createInfoWindow(parkName, truckSpaceRate, standardName, active, normal) {
                let info = document.createElement("div");
                info.className = "custom-info input-card content-window-card";

                //可以通过下面的方式修改自定义窗体的宽高
                info.style.width = "120px";
                // 定义中部内容
                let middle = document.createElement("div");
                let p1 = document.createElement("p");
                let p2 = document.createElement("p");
                middle.className = "info-middle";
                p1.innerHTML = parkName;
                p2.innerHTML = truckSpaceRate;
                middle.appendChild(p1)
                middle.appendChild(p2)
                info.appendChild(middle);

                // 定义底部内容
                let bottom = document.createElement("div");
                bottom.className = "info-bottom";
                bottom.style.position = 'relative';
                bottom.style.top = '0px';
                bottom.style.margin = '0 auto';
                let sharp = document.createElement("img");
                sharp.src = normal;
                let div = document.createElement('div');
                bottom.appendChild(div);
                div.className = "text";
                div.innerText = standardName;
                bottom.appendChild(sharp);
                info.appendChild(bottom);
                return info;
            },
        }
        ,

        destroyed() {
            this.map.destroy();
        }
        ,

        computed: {
            isHasInput() {
                return this.inputContent ? true : false;
            }
            ,

            getCarStatus() {
                return function (status) {
                    if (status == 1) return "空闲"
                    else return "正常";
                }
            }
            ,

            getCarIcon() {
                return function (status) {
                    if (status == 1) return ImageNormal2;
                    return ImageNormal;
                }
            }


        }
    }
</script>

<style scoped>
    html, body, #content, #mapBox {
        width: 100%;
        height: 100%
    }

    #contain-tool {
        position: absolute;
        top: 24px;
        left: 60px;
    }

    /* contain-search */
    #contain-search {
        width: 240px;
        height: 40px;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0px 1px 10px 0px rgba(201, 201, 201, 1);
        display: flex;
        align-items: center;
        margin-left: 10px;
    }

    #contain-search .input-search {
        margin-left: 25px;
        flex: 1 1 auto;
        border: none;
        height: 100%;
        outline: none;
        font-size: 16px;
        color: #020202;
    }

    #contain-search .input-clear {
        cursor: pointer;
        width: 27px;
        height: 38px;
        background: url(//webmap1.bdimg.com/wolfman/static/common/images/new/searchbox_5c0d97d.png) no-repeat 0 -114px #fff;
    }

    #contain-search .icon-search {
        flex: 1 0 auto;
        width: 20px;
        height: 20px;
        margin-left: 10px;
        margin-right: 25px;
        cursor: pointer;
    }

    #edit-area {
        width: 100%;
        height: 100%;
        margin: 10px;
        border: #f7f7f7 1px solid;
        overflow: scroll;
    }

    .title {
        margin: 0;
        border-bottom: rgba(52, 63, 49, 0.3) 1px solid;
        padding: 10px;
    }

    .edit-item {
        display: flex;
        align-items: center;
        margin-left: 50px;
        padding: 10px 0;
    }

    .edit-item .item-text {
        width: 150px;
    }

    .edit-item.tail {
        justify-content: center;
    }

    .edit-item button {
        margin: 0 10px;
    }

    .item-car {
        width: 200px;
        margin-left: 20px;
        margin-top: 20px;
    }

    .item-car .icon-car {
        width: 123px;
        height: 62px;
        margin-bottom: 12px;
    }

    .item-car .text-num {
        font-size: 12px;
        color: #a0a0a0;
        /* flex */
        display: flex;
        align-items: center;
        margin-bottom: 12px;
    }

    .item-car .text-plate {
        color: #a0a0a0;
        font-size: 12px;
    }

    .box-popup-parking {
        min-width: 217px;
        height: 36px;
        line-height: 36px;
        padding: 0 22px;
        border: 1px solid #ccc;
        /* text */
        color: #797979;
        font-size: 12px;
        /* flex */
        display: flex;
    }
</style>
